<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <link rel="stylesheet" type="text/css" href="../css/aui.css" />
</head>
<style>
.aui-bar {padding-top: 20px;}
</style>
<body>
    <header class="aui-bar aui-bar-nav" id="aui-header">
        <a class="aui-btn aui-pull-left" tapmode onclick="closeWin()">
            <span class="aui-iconfont aui-icon-left">消息</span>
        </a>
        <div class="aui-title" id="header-user"></div>
        <a class="aui-pull-right aui-btn aui-btn-outlined" onclick="openWin('chat_history')">
            <span class="aui-iconfont aui-icon-menu"></span>
        </a>
    </header>
</body>
<script type="text/javascript" src="../script/zepto.min.js" ></script>
<script type="text/javascript" src="../script/api.js"></script>
<script type="text/javascript" src="../script/aui-toast.js" ></script>
<script type="text/javascript">
    apiready = function(){
        api.parseTapmode();
        var username = api.pageParam.username;
        var targetId = api.pageParam.targetId;
        var user_img = api.pageParam.user_img;
        var sentTime = api.pageParam.sentTime;
        var groupId = api.pageParam.id;
        var conversationType = api.pageParam.conversationType;

        $("#header-user").html(username);
        var header = $api.byId('aui-header');
        $api.fixStatusBar(header);
        var headerPos = $api.offset(header);
        var body_h = $api.offset($api.dom('body')).h;
        api.openFrame({
            name: 'send_msg_frm',
            url: 'send_msg_frm.html',
            bounces: true,
            rect: {
                x: 0,
                y: headerPos.h,
                w: 'auto',
                h: api.frameHeight-headerPos.h-50
            },
            pageParam: {
               username:username,
               targetId:targetId,
               user_img:user_img,
               sentTime:sentTime,
               groupId:groupId
            }
        })

        //UIChatBox
       var UIChatBox = api.require('UIChatBox');

       UIChatBox.open({
               placeholder : '',
               maxRows : 4,
               emotionPath : 'widget://res/ChatBox/emotion',
               texts : {
                       recordBtn : {
                               normalTitle : '按住  说话',
                               activeTitle : '松开  结束'
                       },
                       sendBtn : {
                               title : '发送'
                       }
               },
               styles : {
                       inputBar : {
                               borderColor : '#ececec',
                               bgColor : '#fbfbfb'
                       },
                       inputBox : {
                               borderColor : '#B3B3B3',
                               bgColor : '#FFFFFF'
                       },
                       emotionBtn : {
                               normalImg : 'widget://res/ChatBox/face1.png'
                       },
                       extrasBtn : {
                               normalImg : 'widget://res/ChatBox/add1.png'
                       },
                       keyboardBtn : {
                               normalImg : 'widget://res/ChatBox/key1.png'
                       },
                       speechBtn : {
                               normalImg : 'widget://res/ChatBox/rec.png'
                       },speechBtn: {                        //（可选项）JSON对象；输入框左侧按钮样式，不传则不显示左边的语音按钮
                                normalImg: 'widget://res/ChatBox/cam1.png'          //字符串类型；左侧按钮常态的背景图片（本地路径，fs://、widget://）
                       },
                       recordBtn : {
                               normalBg : '#ffffff',
                               activeBg : '#F4F4F4',
                               color : '#5D5D5D',
                               size : 14
                       },
                       indicator : {
                               target : 'both',
                               color : '#c4c4c4',
                               activeColor : '#9e9e9e'
                       },
                       sendBtn : {
                               titleColor : '#ffffff',
                               bg : '#12b7f5',
                               activeBg : '#1ba1d4',
                               titleSize : 14
                       }
               },
               extras : {
                       titleSize : 14,
                       titleColor : '#a3a3a3',
                       btns : [{
                               title : '相册',
                               normalImg : 'widget://res/ChatBox/pic.png',
                               activeImg : 'widget://res/ChatBox/pic.png'
                       }, {
                               title : '相机',
                               normalImg : 'widget://res/ChatBox/carm.png',
                               activeImg : 'widget://res/ChatBox/carm.png'
                       }]
               }
       }, function(ret, err) {
               var eventType = ret.eventType;
               var type = ret.index;
               var msg = ret.msg;
               if (eventType == 'send') {
                       if ($api.trimAll(ret.msg) == '') {
                               api.toast({
                                       msg : '不能发送空白消息',
                                       duration : 1000,
                                       location : 'center'
                               });
                       } else {
                               chat(targetId,msg,conversationType);
                       }
               }else if (eventType == 'clickExtras') {
                  if(type==0){
                      getPic('library',targetId);
                  }else if (type==1) {
                      getPic('camera',targetId);
                  }
               }

       });

       //当前会话用户id和当前会话历史消息从消息列表页点击传递进来
       targetId = api.pageParam.targetId;
       historyMessages = api.pageParam.historyMessages;

       var sj1="";
       var toast = new auiToast();
       //监听 press（按下录音按钮）
        UIChatBox.addEventListener({
            target: 'recordBtn',
            name: 'press'
        }, function(ret, err) {
            if (ret) {
              sj1 = new Date().getTime();
              api.showProgress({
                 style: 'default',
                 animationType: 'fade',
                 title: '录音中...',
                 text: '手指上划，取消发送',
                 modal: false
              });
              api.startRecord({
                  path: 'fs://ygg_' + (+new Date()) + '.amr'
              });
            } else {
              api.toast({
                  msg:'位置错误'
              });
            }
        });

        //监听 press_cancel（松开录音按钮）
         UIChatBox.addEventListener({
             target: 'recordBtn',
             name: 'press_cancel'
         }, function(ret, err) {
            var sj2 = new Date().getTime() - sj1;
            if (sj2 <= 2000) {
                    api.hideProgress();
                    api.stopRecord();
                    api.toast({
                            msg : '语音时间较短，请重新录音',
                            duration : 2000,
                            location : 'middle'
                    });
            }else if (sj2 > 2000) {
                if (ret) {
                       api.stopRecord(function(ret, err) {
                       if (ret) {
                           api.hideProgress();
                           var path = ret.path;
                           var duration = ret.duration;
                           sendVoice(targetId,path,duration);
                       }
                     });

                  } else {
                    api.toast({
                        msg:'未知错误'
                    });
                  }
            }
         });

         //监听 按下录音按钮后，从按钮移出并松开按钮
          UIChatBox.addEventListener({
              target: 'recordBtn',
              name: 'move_out_cancel'
          }, function(ret, err) {
              if (ret) {
                   api.stopRecord(function(ret, err) {
                   if (ret) {
                       api.hideProgress();
                   }
                 });
              } else {
                api.toast({
                    msg:'未知错误'
                });
              }
          });

          //监听 press_cancel（松开录音按钮）
           UIChatBox.addEventListener({
               target: 'recordBtn',
               name: 'move_in'
           }, function(ret, err) {
               if (ret) {
                 api.startRecord({
                     path: 'fs://ygg_' + (+new Date()) + '.amr'
                 });
               } else {
                 api.toast({
                     msg:'未知错误'
                 });
               }
           });

    };

    function closeWin(){
        api.closeWin({
        });
    }

    var targetId,historyMessages;
    //发送聊天
    function chat(targetId,msg,conversationType){
        //向会话列表页发送消息事件
        api.sendEvent({
            name:'sendMessage',
            extra:{
                type:'text',
                targetId:''+targetId+'',
                content: msg,
                conversationType:conversationType,
                extra:''
            }
        })
    }

    //发送语音聊天
    function sendVoice(targetId,voicePath,duration){
        //alert(voicePath);
        //向会话列表页发送消息事件
        api.sendEvent({
            name:'sendVoice',
            extra:{
                type:'voice',
                targetId:''+targetId+'',
                voicePath: voicePath,
                duration:duration,
                conversationType:'PRIVATE',
                extra:''
            }
        })
    }

    //选择图片
    function getPic(type,targetId){
        api.getPicture({
            sourceType: type,
            encodingType: 'jpg',
            mediaValue: 'pic',
            destinationType: 'url',
            allowEdit: false,
            quality: 100,
            targetWidth: 200,
            targetHeight: 200,
            saveToPhotoAlbum: false
        }, function(ret, err) {
            if (ret) {
                api.sendEvent({
                    name:'sendPic',
                    extra:{
                        type:'image',
                        targetId:''+targetId+'',
                        imagePath: ret.data,
                        conversationType:'PRIVATE'
                    }
                })
            } else {
              api.toast({
                  msg:'取消发送'
              });
            }
        });
    }

    function  closeBoard(){
        var UIChatBox = api.require('UIChatBox');
        UIChatBox.closeBoard();
    }


    function openWin(name) {
        var targetId = api.pageParam.targetId;
        api.openWin({
            name: name,
            url: name+'_win.html',
            pageParam:{
               targetId:targetId
            }
        });
    }


</script>
</html>
